<template>
    <div class="timekeep">
        <titleBar title="计时器" theme="dark" />  
        <div class="title-name">{{
            type === 1 ? '累计用时(未开始)' :
            type === 2 ? '累计用时(计时中)' :
            type === 3 ? '累计用时(暂停中)' :
            type === 4 ? '累计用时(已完成)' :
            '未知状态'
        }}</div>
<!--         
        <div class="title-name" v-if="type === 1">累计用时(未开始) </div>
        <div class="title-name" v-if="type === 1">累计用时(计时中) </div>
        <div class="title-name" v-if="type === 1">累计用时(暂停中) </div>
        <div class="title-name" v-if="type === 1">累计用时(已完成) </div>
        <div class="title-name" v-if="type === 1">未知状态 </div> -->
        
        <div class="flex timekepping-show flex-center-x flex-center-y" v-bind:style="{color: type === 2 ? '#fff' : '#959595'}">
            <div class="block">{{timekeepDate.h}}</div>
            <div class="gap">:</div>
            <div class="block">{{timekeepDate.m}}</div>
            <div class="gap">:</div>
            <div class="block">{{timekeepDate.s}}</div>
        </div>
        <div class="days flex">
            <div class="inner">
                <div class="item" v-for="(item, index) in tabInfo.list" :key="index" v-on:click="switchOptions(index)">
                    <span :class="index === tabInfo.activeIndex ? 'active' : ''">{{item.name}}</span>
                </div>
            </div>
        </div>
        <div class="day-list-box" v-if="type !== -1">
            <div class="day-list-title flex">
                <div v-for="(item, index) in [
                    '时节',
                    '开始时间',
                    '结束时间',
                    '用时',
                ]" 
                v-text="item"
                :key="index" />
            </div>
            <div class="day-list">
                <div class="flex item" v-for="(item, index) in daylist" :key="index">
                    <div>{{item.index}}</div>
                    <div v-html="showTime(item.beginDate)"></div>
                    <div v-html="showTime(item.endDate)"></div>
                    <div v-html="hmsvToShowTime(item.totalTime)"></div>
                </div>
                <div class="nil-data" v-if="daylist.length === 0 && detailStatus === 0">加载中</div>
                <div class="nil-data" v-if="daylist.length === 0 && detailStatus === 1">暂无数据</div>
            </div>
        </div>
        <div v-else>
            <div class="nil-data">加载中..</div>
        </div>
    </div>
</template>
<script>
import titleBar from '@/components/title_bar/index.vue'
import { Timekeeps, HMS2S } from '@/utils/date.js'
import { Copy } from '@/utils/object'
let m_image = ''
let s_image = ''
const defaultTimekeepDate = {h: '00', m: '00', s: '00'}
export default {
    components: {
        titleBar,
    },
    data(){
        return {
            timekeepDate: defaultTimekeepDate,
            type: 1,
            days: [''],
            tabInfo: {
                /**
                 * [
                 *  {name: 'String'}
                 * ]
                 */
                list: [],
                activeIndex: 0,
            },
            daylist: [],
            // 详情状态  -1 未加载数据    0 加载中   1 加载完成
            detailStatus: -1,
            // orderUid
            orderUid: 0,
            timekeep: null,
            // 计时任务
            taskId: 0,
            // 计时器执行
            timeing: true,
            currentSwitch: {}
        }
    },
    async created(){
        let orderUid = this.$route.query?.uid
        if(!orderUid){
            this.$toast('UID不存在')
            return
        }
        // TODO 定时刷新
        let params = {
            orderUid,
        }
        let dateResponse = await HTTP('orderChronograph/selectPreordainDateByUid', params)
        if(dateResponse.code !== 200){
            this.$toast('异常')
            return
        }
        console.log('设计师计时器列表')
        console.log(dateResponse.data)
        this.tabInfo = {
            list: dateResponse.data.map(e => {
                return {
                    ...e,
                    name: e.preordainDate.split(' ')[0]
                }
            }),
            activeIndex: 0,
        }
        if(dateResponse.data.length == 0){
            return
        }
        this.orderUid = orderUid
        // 初始化计时器
        this.timekeep = Timekeeps()
        // 记录当前TaskId
        this.taskId = this.timekeep.getTaskId()
        let loop = (i) => {
            if(!this.timeing){
                return
            }
            this.timekeep.end()
                setTimeout(() => {
                // console.log(this.currentSwitch.preordainDate)
                // console.log(dateResponse.data[0].preordainDate)
                // if(this.currentSwitch.preordainDate && this.currentSwitch.preordainDate !== dateResponse.data[0].preordainDate){
                //     loop(i + 1)
                //     return
                // }
                this.getList({
                    orderUid,
                    preordainDate: this.currentSwitch.preordainDate ? this.currentSwitch.preordainDate.split(' ')[0]
                        : dateResponse.data[0].preordainDate.split(' ')[0]
                })
                loop(i + 1)
            }, i === 0 ? 0 : 5e3)
        }
        loop(0)
    },
    methods: {
        hmsvToShowTime(hmsv){
            return hmsv.split(':').map((e, i) =>  i === 0 ? e + ':' : 
                i === 1 ? e + `<img style="height: 0.9em" src="${m_image}" />` : 
                i === 2 ? e + `<img style="height: 0.9em" src="${s_image}" />` : 
                e
            ).join('')
        },
        showTime(timev){
            if(!timev){
                return ''
            }
            return this.hmsvToShowTime(timev.split(' ')[1])
        },
        // 开始计时，根据当前时间继续计时
        /**
         * timeStar hh:mm:ss
         * addnumber number
         */
        startTimeKeep(timeStr, addNumber, taskId) {
            this.timekeep.start((e) => {
                if(this.type === 2){
                    this.timekeepDate = e
                }
            }, {
                n: HMS2S(timeStr, ':') + addNumber,
                taskId
            })
        },
        // 根据时间获取列表详情（包括上面的详情）
        async getList(params){
            let listResponse
            let countTime
            try {
                // 清空上一次数据
                // this.daylist = []
                // 加载中状态
                this.detailStatus = 0
                // TEST 测试加载状态的展示  延时模拟
                await new Promise((resolve) => setTimeout(resolve, 500))
                listResponse = await HTTP('orderChronograph/selectOrderChronographInfo', params)
            } catch (error) {
                this.$toast('数据开小差了')
                return
            }
            // console.log('设计师计时器列表详情')
            // console.log(listResponse.data)
            if(listResponse.code !== 200){
                this.$toast(listResponse.msg || '服务器异常')
                return
            }
            this.daylist = listResponse.data.orderChronographs.map((e, i) => ({...e, 
                index: i + 1
            }))
            this.type = listResponse.data.type
            // 加载完成状态
            this.detailStatus = 1
            countTime = listResponse.data.countTime
            if(this.type === 2){
                // countTime
                this.startTimeKeep(countTime, 0, this.taskId)
            }else{
                this.timekeep.end()
                this.timekeepDate = {
                    h: countTime.split(':')[0],
                    m: countTime.split(':')[1],
                    s: countTime.split(':')[2],
                }
            }
        },
        // TODO 数据缓存处理。（历史数据可以缓存，因为历史数据不可修改）
        switchOptions(index) {
            let detailParams = this.tabInfo.list[index]
            this.currentSwitch = Copy(detailParams)
            // 已加载数据，不进行切换，如有需求需要写入堆栈阔以在这里
            if(this.detailStatus === 0){
                return
            }
            // 获取数据
            console.log(detailParams)
            if(!this.orderUid){
                console.log('异常： 找不到orderUid')
                return
            }
            // 未加载数据 并且 获取到了请求参数之后再进行切换
            this.tabInfo.activeIndex = index
            // 结束当前计时
            this.timekeep.end(this.taskId)
            // 重置数据
            // this.timekeepDate = Copy(defaultTimekeepDate)
            // 获取数据
            this.getList({
                orderUid: this.orderUid,
                preordainDate: detailParams.preordainDate.split(' ')[0]
            })
        },
        async onstop(){
        },
        async oncontinue(){            
        },
        async done(){
        }
    },
    destroyed(){
        // console.log('离开')
        // 释放所有计时资源
        this.timekeep.end()
        // 清空定时器
        this.timeing = false
    }
}
</script>
<style lang="scss" scoped>
@import './style.scss';
</style>


